<?php
declare (strict_types=1);

namespace app\common\service;

use app\common\enum\file\FileTypeEnum;
use app\common\enum\SettingEnum;
use app\common\model\AttachmentModel;
use app\common\model\SettingModel;

class AttachmentService extends BaseService
{
    // 表单上传
    public function upload($user_id = 0) : array
    {
        // 实例化存储驱动
        $config = SettingModel::getItem(SettingEnum::STORAGE);
        $storage = new \app\common\library\storage\Driver($config);

        // 设置和验证文件的信息
        $storage->setUploadFile('file')
            ->setRootDirName('upload')
            ->setValidationScene('image')
            ->validate();

        // 执行文件上传
        if (!$storage->upload()) {
            return render_array_error('上传失败：' . $storage->getError());
        }

        // 文件信息
        $file_info = $storage->getSaveFileInfo();

        // 添加文件库记录
        $AttachmentModel = new AttachmentModel();
        $AttachmentModel->add($file_info, FileTypeEnum::IMAGE, $user_id);

        // 上传成功
        return render_array_success(['file_info' => $AttachmentModel->toArray()], '上传成功');
    }
}
